package com.scoy.honeymei.activity.mall;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.scoy.honeymei.R;
import com.scoy.honeymei.activity.me.AddressListActivity;
import com.scoy.honeymei.adapter.OrderAdapter;
import com.scoy.honeymei.base.BaseActivity;
import com.scoy.honeymei.bean.AddressBean;
import com.scoy.honeymei.bean.GoodsOrderBean;
import com.scoy.honeymei.bean.OrderBean;
import com.scoy.honeymei.dialog.TicketCheckDialog;
import com.scoy.honeymei.http.HpCallback;
import com.scoy.honeymei.http.HpGo;
import com.scoy.honeymei.url.ApiCallBack;
import com.scoy.honeymei.url.MeConstant;
import com.scoy.honeymei.url.MyUrl;
import com.scoy.honeymei.utils.LogUtil;
import com.scoy.honeymei.utils.MyUtil;
import com.scoy.honeymei.utils.SPHelper;
import com.scoy.honeymei.utils.SystemUtil;
import com.scoy.honeymei.wxapi.PayEvent;
import com.scoy.honeymei.wxapi.PayResultActivity;
import com.scoy.honeymei.wxapi.PayUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @ClassName: PaySureActivity$
 * @Description: 确认订单界面
 * @Author: GaoZhan
 * @CreateDate: 2019/9/10/0010$ 上午 9:22$
 * @UpdateUser: 更新者
 * @UpdateDate: 2019/9/10/0010$ 上午 9:22$
 * @UpdateRemark: 更新内容
 */
public class PaySureActivity extends BaseActivity {

    @BindView(R.id.back_iv)
    ImageView backIv;
    @BindView(R.id.title_tv)
    TextView titleTv;
    @BindView(R.id.sign_tv)
    TextView signTv;
    @BindView(R.id.title_llt)
    LinearLayout titleLlt;
    @BindView(R.id.ps_noadd_tv)
    TextView psNoaddTv;
    @BindView(R.id.ps_iv0)
    ImageView psIv0;
    @BindView(R.id.ps_name_tv)
    TextView psNameTv;
    @BindView(R.id.ps_phone_tv)
    TextView psPhoneTv;
    @BindView(R.id.ps_addressdetail_tv)
    TextView psAddressdetailTv;
    @BindView(R.id.ps_havead_cl)
    ConstraintLayout psHaveadCl;
    @BindView(R.id.ps_address_cl)
    ConstraintLayout psAddressCl;
    @BindView(R.id.ps_rv)
    RecyclerView psRv;
    @BindView(R.id.ps_tv1)
    TextView psTv1;
    @BindView(R.id.ps_leavemes_et)
    EditText psLeavemesEt;
    @BindView(R.id.ps_allmoney_tv)
    TextView psAllmoneyTv;
    @BindView(R.id.ps_ok_tv)
    TextView psOkTv;
    @BindView(R.id.ps_freight_tv)
    TextView psFreightTv;
    @BindView(R.id.ps_ticketcheck_tv)
    TextView psTicketcheckTv;
    private PaySureActivity mContext;
    private ArrayList<OrderBean> datalist;
    private GoodsOrderBean goodsOne;
    private int type;
    private int numOne;
    private String payType = "null";
    private String ids;
    private OrderAdapter orderAdapter;
    private boolean isaddress;
    private String freight = "0.00";
    private int shopNum = 1;
    private String payThree;

    private int shopId = 0;
    private int couponId = 0;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_create);
        ButterKnife.bind(this);
        mContext = PaySureActivity.this;
        type = getIntent().getIntExtra("type", 0);
        shopId = getIntent().getIntExtra("shopId", 0);
        goodsOne = getIntent().getParcelableExtra("goodsBean");
        ids = getIntent().getStringExtra("ids");

        initNormal();

        httpNorAddress();
    }

    @Override
    public void initNormal() {
        datalist = new ArrayList<>();

        titleTv.setText(R.string.sureorder);

        MyUtil.setStatusBar(mContext, getWindow(), true, R.color.colorWhite);
        titleLlt.setPadding(0, MyUtil.getStatusBarHeight(mContext), 0, 0);

        EventBus.getDefault().register(this);
    }

    private void initUI() {
        if (type == 1) {
            //详情立即购买


            datalist.add(new OrderBean(goodsOne.getShop_name(), goodsOne.getShop_id(), new ArrayList<GoodsOrderBean>() {{
                add(goodsOne);
            }}));
            freight=goodsOne.getFreight();
            meet=goodsOne.getMeet_money();
            shopNum = 1;
            numOne = goodsOne.getNumber();
            psAllmoneyTv.setText("￥" + getAllMoney(datalist));
            payThree = goodsOne.getPaytype();

        } else if (type == 2) {
            //购物车购买


            httpCartData(ids);
        }

        initRV();
    }

    private void initRV() {
        orderAdapter = new OrderAdapter(mContext, datalist);
        psRv.setLayoutManager(new LinearLayoutManager(mContext, RecyclerView.VERTICAL, false));
        psRv.setAdapter(orderAdapter);

        //sub
        orderAdapter.setOnOneClick((pos, posin) -> {
            GoodsOrderBean goodsOrderBean = datalist.get(pos).getGoodsList().get(posin);
            int number = goodsOrderBean.getNumber();
            if (number > 1) {
                goodsOrderBean.setNumber(number - 1);
                orderAdapter.notifyDataSetChanged();
                if (type == 1) {
                    numOne = number - 1;
                } else {
                    httpCartChange(mContext, goodsOrderBean.getGoodscarid(), 2);
                }
                mCouponMoney="";
                psTicketcheckTv.setText("");
                couponId = 0;
                psAllmoneyTv.setText("￥" + getAllMoneyAndCouPon(datalist));
            }
        });

        //add
        orderAdapter.setOnTwoClick((pos, posin) -> {
            GoodsOrderBean goodsOrderBean = datalist.get(pos).getGoodsList().get(posin);
            int number = goodsOrderBean.getNumber();
            goodsOrderBean.setNumber(number + 1);
            orderAdapter.notifyDataSetChanged();
            if (type == 1) {
                numOne = number + 1;
            } else {
                httpCartChange(mContext, goodsOrderBean.getGoodscarid(), 1);
            }
            mCouponMoney="";
            psTicketcheckTv.setText("");
            couponId = 0;
            psAllmoneyTv.setText("￥" + getAllMoneyAndCouPon(datalist));

        });

    }

    @OnClick({R.id.back_iv, R.id.ps_address_cl, R.id.ps_ok_tv, R.id.ps_ticketcheck_tv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back_iv:
                finish();
                break;
            case R.id.ps_address_cl:
                Intent intent = new Intent(mContext, AddressListActivity.class);
                intent.putExtra("wy", 1);
                startActivityForResult(intent, 0x114);
                break;
            case R.id.ps_ok_tv:
                if (isaddress) {
                    showdialog();
                } else {
                    MyUtil.mytoast(mContext, "请选择收货地址");
                }
                break;
            case R.id.ps_ticketcheck_tv:
                TicketCheckDialog.newInstance(shopId, getAllMoney2(datalist)).setOnDialogListener(ccBean -> {
                    String money = ccBean.getMoney();
                    mCouponMoney=money;
                    psTicketcheckTv.setText("优惠：" + money);
                    couponId = ccBean.getId();
                    psAllmoneyTv.setText("￥" + getAllMoneyAndCouPon(datalist));
                }).show(getSupportFragmentManager(), "");
                break;
        }
    }
private String mCouponMoney="";
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode) {
            case 0x124:
                AddressBean address = (AddressBean) data.getParcelableExtra("address");
                if (address != null) {
                    psNoaddTv.setVisibility(View.GONE);
                    psHaveadCl.setVisibility(View.VISIBLE);
                    psNameTv.setText(address.getUsername());
                    psPhoneTv.setText(address.getPhone());
                    psAddressdetailTv.setText(address.getArea() + address.getAddressdetail());
                    httpCheck(address.getId());
                    isaddress = true;

                }
                break;
            case 0x87:
                setResult(0x87);
                finish();
                break;
        }
    }
    private String meet="0.00";
    //购物车购买信息
    private void httpCartData(String adId) {
        HttpParams params = new HttpParams();
        params.put("userid", SPHelper.getString(MeConstant.UID, ""));
        params.put("ids", adId);
        HpGo.newInstance().HttpGo(mContext, MyUrl.ORDER_CARTE_GOODS, params, new ApiCallBack() {
            @Override
            public void onSuccess(String o) {
                List<OrderBean> data = new Gson().fromJson(o, new TypeToken<List<OrderBean>>() {
                }.getType());
                shopNum = data.size();
                if (data.size() > 0) {
                    OrderBean orderBean = data.get(0);
                    payThree = orderBean.getPaytype();
                }
                freight=getIntent().getStringExtra("freight");
                meet=getIntent().getStringExtra("meet");

//                psFreightTv.setText("￥" + Double.parseDouble(freight) * shopNum);

                datalist.addAll(data);
                psAllmoneyTv.setText("￥" + getAllMoney(datalist));
                orderAdapter.notifyDataSetChanged();

            }
        });

    }

    //获取默认地址信息
    private void httpNorAddress() {
        HttpParams params = new HttpParams();
        params.put("userid", SPHelper.getString(MeConstant.UID, ""));
        HpGo.newInstance().HttpGo(mContext, MyUrl.GET_NORMAL_ADDRESS, params, new ApiCallBack() {
            @Override
            public void onSuccess(String o) {
                AddressBean address = new Gson().fromJson(o, AddressBean.class);
                if (address.getUsername() == null && address.getPhone() == null) {
                    psNoaddTv.setVisibility(View.VISIBLE);
                    psHaveadCl.setVisibility(View.GONE);
                } else {
                    psNoaddTv.setVisibility(View.GONE);
                    psHaveadCl.setVisibility(View.VISIBLE);
                    psNameTv.setText(address.getUsername());
                    psPhoneTv.setText(address.getPhone());
                    psAddressdetailTv.setText(address.getArea() + address.getAddressdetail());
                    isaddress = true;
//                    freight = address.getFreight();
                }
                initUI();
            }
        });

    }

    //选择地址
    private void httpCheck(int adId) {
        HttpParams params = new HttpParams();
        params.put("userid", SPHelper.getString(MeConstant.UID, ""));
        params.put("id", adId);
        HpGo.newInstance().HttpGo(mContext, MyUrl.SELECT_ADDRESS, params, new ApiCallBack() {
            @Override
            public void onSuccess(String o) {
                AddressBean address = new Gson().fromJson(o, AddressBean.class);
//                freight = address.getFreight();
//                psFreightTv.setText("￥" + Double.parseDouble(address.getFreight()) * shopNum);
                psAllmoneyTv.setText("￥" + getAllMoney(datalist));
            }

        });

    }

    //修改购物车数量
    private void httpCartChange(Context context, int ids, int status) {
        HttpParams params = new HttpParams();
        params.put("id", ids);
        params.put("status", status);//1为增加 2为减少
        OkGo.<String>post(MyUrl.CART_CHANGE_NUM).params(params).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                String body = response.body();
                LogUtil.e(body);
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                MyUtil.mytoast(context, response.toString());
            }
        });

    }

    /**
     * 选择弹窗
     */
    private void showdialog() {
        final Dialog dialogpay = new Dialog(this, R.style.BottomDialogStyle);
        View view = View.inflate(this, R.layout.dialog_tocheckpay_wallet, null);

        ImageView imgClose = view.findViewById(R.id.imgClose);
        Button btnSure = view.findViewById(R.id.btnSure);
        TextView alipayTv = view.findViewById(R.id.txtZhifubao);
        TextView wxpayTv = view.findViewById(R.id.txtWechat);
        TextView walletTv = view.findViewById(R.id.txtWallet);

        dialogpay.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                payType = "null";
            }
        });

        imgClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialogpay.dismiss();
            }
        });
        alipayTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alipayTv.setSelected(true);
                wxpayTv.setSelected(false);
                walletTv.setSelected(false);
                payType = "alipay";
            }
        });
        walletTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                walletTv.setSelected(true);
                wxpayTv.setSelected(false);
                alipayTv.setSelected(false);
                payType = "balance";
            }
        });
        wxpayTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alipayTv.setSelected(false);
                wxpayTv.setSelected(true);
                walletTv.setSelected(false);
                payType = "wechat";
            }
        });


        btnSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!"null".equals(payType)) {
                    if (type == 1) {
                        payNow(payType);
                    } else if (type == 2) {
                        payCart(payType);
                    }
                    dialogpay.dismiss();
                }
            }
        });

        dialogpay.setContentView(view);
        dialogpay.setCanceledOnTouchOutside(true);
        Window dialogWindow = dialogpay.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (SystemUtil.getScreenWidth(mContext));
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.gravity = Gravity.BOTTOM;
        dialogWindow.setAttributes(lp);
        dialogpay.show();

    }


    //详情去购买
    private void payNow(String payType) {
        HttpParams params = new HttpParams();
        params.put("userid", SPHelper.getString(MeConstant.UID, ""));
        params.put("id", goodsOne.getId());
        params.put("number", numOne);
        params.put("content", psLeavemesEt.getText().toString());
        params.put("type", payType);
        params.put("coupon_id", couponId);

        HpGo.newInstance().HttpGo(mContext, MyUrl.PAY_NOW_GOODS, params, new ApiCallBack() {
            @Override
            public void onSuccess(String o) {
                if ("false".equals(o)) {
                    MyUtil.mytoast(mContext, "支付错误");
                    return;
                }
                if ("balance".equals(payType)) {
                    payBalance(o);
                } else {
                    PayUtil.toPayPayPay(mContext, payType, o);//支付
                }
            }
        });

    }

    //购物车去购买
    private void payCart(String payType) {
        HttpParams params = new HttpParams();
        params.put("userid", SPHelper.getString(MeConstant.UID, ""));
        params.put("ids", ids);
        params.put("content", psLeavemesEt.getText().toString());
        params.put("type", payType);
        params.put("coupon_id", couponId);

        HpGo.newInstance().HttpGo(mContext, MyUrl.PAY_CART_GOODS, params, new ApiCallBack() {
            @Override
            public void onSuccess(String o) {
                if ("false".equals(o)) {
                    MyUtil.mytoast(mContext, "支付错误");
                    if (type == 2) {
                        setResult(0x87);
                        finish();
                    }
                    return;
                }
                if ("balance".equals(payType)) {
                    payBalance(o);
                } else {
                    PayUtil.toPayPayPay(mContext, payType, o);//支付
                }

            }
        });

    }

    private String getAllMoney(ArrayList<OrderBean> datalist) {
        double allPrice = 0;

        for (OrderBean spbean : datalist) {
            List<GoodsOrderBean> goodsList = spbean.getGoodsList();
            for (GoodsOrderBean gbean : goodsList) {
                allPrice += Double.parseDouble(gbean.getMoney()) * gbean.getNumber();
            }
        }
        if(allPrice>=Double.parseDouble(meet)){

            psFreightTv.setText("￥ 0.00");
        }else {
            allPrice= allPrice+Double.parseDouble(freight);
            psFreightTv.setText("￥" + freight );
        }
//        if(!mCouponMoney.isEmpty()){
//            allPrice=allPrice-Double.parseDouble(mCouponMoney);
//        }
        return MyUtil.doubleTo2String(allPrice);
    }
    private String getAllMoney2(ArrayList<OrderBean> datalist) {
        double allPrice = 0;

        for (OrderBean spbean : datalist) {
            List<GoodsOrderBean> goodsList = spbean.getGoodsList();
            for (GoodsOrderBean gbean : goodsList) {
                allPrice += Double.parseDouble(gbean.getMoney()) * gbean.getNumber();
            }
        }
//        if(allPrice>=Double.parseDouble(meet)){
//            allPrice= allPrice+Double.parseDouble(freight);
//            psFreightTv.setText("￥ 0.00");
//        }else {
//            psFreightTv.setText("￥" + freight );
//        }
//        if(!mCouponMoney.isEmpty()){
//            allPrice=allPrice-Double.parseDouble(mCouponMoney);
//        }
        return MyUtil.doubleTo2String(allPrice);
    }
    private String getAllMoneyAndCouPon(ArrayList<OrderBean> datalist) {
        double allPrice = 0;
//        double allPrice = 0.0 + Double.parseDouble(freight) * shopNum;

        for (OrderBean spbean : datalist) {
            List<GoodsOrderBean> goodsList = spbean.getGoodsList();
            for (GoodsOrderBean gbean : goodsList) {
                allPrice += Double.parseDouble(gbean.getMoney()) * gbean.getNumber();
            }
        }
        if(allPrice>=Double.parseDouble(meet)){

            psFreightTv.setText("￥ 0.00");
        }else {
            allPrice= allPrice+Double.parseDouble(freight);
            psFreightTv.setText("￥" + freight );
        }
        if(!mCouponMoney.isEmpty()){
            allPrice=allPrice-Double.parseDouble(mCouponMoney);
        }

        return MyUtil.doubleTo2String(allPrice);
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onPayEvent(PayEvent event) {
        int type7 = event.getType();//0 成功 -1失败 -2取消
        if (type7 == 0) {
            startActivityForResult(new Intent(mContext, PayResultActivity.class), 0x145);

        } else if (type7 == -1) {
            MyUtil.mytoast(mContext, "支付失败");
        } else {
            MyUtil.mytoast(mContext, "支付取消");
        }

        if (type == 2 && type7 != 0) {
            setResult(0x87);
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    //余额购买
    private void payBalance(String o) {
        HttpParams params = new HttpParams();
        params.put("orderid", o);

        HpGo.newInstance().HttpGo(mContext, MyUrl.ORDER_BALANCE_GOODS, params, new HpCallback() {
            @Override
            public void onSuccess(String o) {
                /*MyUtil.mytoast0(mContext, "支付成功", R.mipmap.ic_sure);
                setResult(0x87);
                finish();*/
                startActivityForResult(new Intent(mContext, PayResultActivity.class), 0x145);
            }

            @Override
            public void onFailed(String code, String msg, String o) {
                MyUtil.mytoast(mContext, msg);
                if (type == 2) {
                    setResult(0x87);
                    finish();

                }
            }

            @Override
            public void onError(int code, String errorMsg) {
                MyUtil.mytoast(mContext, errorMsg);
                setResult(0x87);
                finish();
            }
        });

    }


}
